package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.bean.CompanyBankCard;
import cn.net.shuxing.yifu.common.mapper.CompanyBankCardMapper;
import cn.net.shuxing.yifu.common.util.CommonExample;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CompanyBankCardService extends BaseService<CompanyBankCard,CompanyBankCardMapper> {

    public boolean insert(String openBank,String bankCardNum, String holderName)
    {
        if (!insertable(bankCardNum))
        {
            return false;
        }
        CompanyBankCard companyBankCard = new CompanyBankCard();
        companyBankCard.setBankCardNum(bankCardNum);
        companyBankCard.setHolderName(holderName);
        companyBankCard.setOpenBank(openBank);
        insert(companyBankCard);
        return true;
    }

    public CompanyBankCard getDefaultBankCard()
    {
        CommonExample example = new CommonExample(CompanyBankCard.class);
        example.equals("isDefault",1);
        List<CompanyBankCard> companyBankCards = getsByExampleWithoutComplete(example);
        if (companyBankCards != null && companyBankCards.size() == 1)
            return companyBankCards.get(0);
        else
        {
            if (companyBankCards != null && !companyBankCards.isEmpty())
            {
                for (int i = 0; i < companyBankCards.size() - 1; i++) {
                    CompanyBankCard companyBankCard = companyBankCards.get(i);
                    companyBankCard.setIsDefault(0);
                    update(companyBankCard);
                    companyBankCards.remove(i);
                }
                return companyBankCards.get(0);
            }
        }
        return null;
    }

    public boolean setDefaultBankCard(Integer bankCardId)
    {
        CompanyBankCard defaultBankCard = getByPrimaryKeyWithoutComplete(bankCardId);
        if (defaultBankCard == null)
            return false;

        CompanyBankCard oldDefaultBankCard = getDefaultBankCard();
        if (oldDefaultBankCard != null)
        {
            oldDefaultBankCard.setIsDefault(0);
            update(oldDefaultBankCard);
        }
        defaultBankCard.setIsDefault(1);
        update(defaultBankCard);
        return true;

    }

    public boolean insertable(String bankCardNum)
    {
        CommonExample example = new CommonExample(CompanyBankCard.class);
        example.equals("bankCardNum",bankCardNum);
        List<CompanyBankCard> companyBankCards = getsByExampleWithoutComplete(example);
        if (companyBankCards != null && !companyBankCards.isEmpty())
            return false;
        return true;
    }
}
